<?php
namespace Home\Common\Controller;
use Home\Controller\CarController;
use Home\Controller\IndexController;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/20
 * Time: 9:33
 */
class CommonController extends \Think\Controller
{
    public  function  __construct(){
        parent::__construct();
        //查找公共部分数据
        //查找所有的友链数据
        $links=M('links')->select();
        $this->assign('links',$links);
        //导航栏，种类，及种类商品推荐
        $nature=$this->nature();
        $this->assign('nature',$nature);
        //搜索框下面的三条数据
        $hot=$this->hot();
        $this->assign('hot',$hot);
        if(isset($_SESSION['uid'])){
            $cars=$this->cars();
            if(empty($cars['cars'])){
              $cars['cars']=0;
            }
        }else{
            $cars['cars']=0;
        }
        $this->assign('cars',$cars['cars']);
//        dd($nature);
        if(method_exists(this,'__init')){
            $this->__init();
        }
    }
    private function nature(){
      $nature=M('nature')->select();
      foreach($nature as $k=>$v){
          $nid=$v['nid'];
            $nature[$k]['goods']=M('goods')->where("nid=$nid")->limit(6)->select();
      }
     return $nature;
    }
    //搜索框下面的三条数据
    private function hot(){
        return M('goods')->where('hot=1 AND status=1')->order('gid desc')->limit(3)->select();
    }



    /**
     * 找出某个分类的子类
     */
    public function finson($cid, $data,$default=null)
    {
        static $arr = [];
        //防止两次调用时静态变量叠加
        if(!is_null($default)){
           $arr=[];
        }
        foreach ($data as $k => $v) {
            if ($cid == $v['sid']) {
                $arr[] = $v['cid'];
                $this->finson($v['cid'], $data);
            }
        }
        return $arr;
    }

    //购物车中商品数量
    private function cars(){
        $uid=session('uid');
        return M('usergoods')->field('sum(count) cars')->where("uid={$uid} AND gstatus=0")->find();
    }

}